package com.psa.element;

import android.content.ContentValues;
import android.database.Cursor;
import com.google.gson.Gson;
import com.psa.tool.DBTool;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author david
 * @date 2016-08-03
 */
public class QuerySetting implements IJson,ISqlObject{
    public int ID = 0;
    public String NAME = "";
    public String KEY = "";
    public String SETTING = "";
    public int SCOPE = 0;


    @Override
    public String toJson() {
        return new Gson().toJson(this);
    }

    @Override
    public int insert(DBTool dbTool) {
        ContentValues values = new ContentValues();
        values.put("ID", ID);
        values.put("name", NAME.trim());
        values.put("key", KEY.trim());
        values.put("setting", SETTING.trim());
        values.put("scope", SCOPE);
        return  (int)dbTool.insert("QuerySetting", values);
    }

    @Override
    public int update(DBTool dbTool) {
        return 0;
    }

    @Override
    public int delete(DBTool dbTool) {
        return 0;
    }

    @Override
    public ISqlObject full(Cursor cursor) {
        if (cursor!=null && cursor.moveToNext()) {
            QuerySetting querySetting = new QuerySetting();
            querySetting.ID = cursor.getInt(0);
            querySetting.NAME = cursor.getString(1);
            querySetting.KEY = cursor.getString(2);
            querySetting.SETTING = cursor.getString(3);
            querySetting.SCOPE = cursor.getInt(4);
            return querySetting;
        }
        return null;
    }

    @Override
    public void clear(DBTool dbTool) {
        dbTool.delete("QuerySetting", "ID Like ?", new String[]{"%"});
    }

    @Override
    public String getDataSql() {
        return "QuerySetting";
    }

    @Override
    public String getSyncMethod() {
        return "getdataobjects";
    }

    @Override
    public String toString() {
        return NAME;
    }

    public static List<QuerySetting> getQuerySettings(String sql) {
        List<QuerySetting> querySettings = new ArrayList<QuerySetting>();
        Cursor cursor = DBTool.getInstance().query(sql);
        QuerySetting setting = new QuerySetting();
        while ((setting=(QuerySetting)setting.full(cursor))!=null) {
            querySettings.add(setting);
        }
        return querySettings;
    }

    public static List<QuerySetting> getQuerySettingList(int scope) {
        String s = scope<0?"'%'":String.valueOf(scope);
        return getQuerySettings("Select * From QuerySetting Where scope like " + s);
    }

    public static List<QuerySetting> getGlobal() {
        return getQuerySettingList(0);
    }

    public static List<QuerySetting> getCustomerScope() {
        return getQuerySettingList(1);
    }

    public static List<QuerySetting> getAll() {
        return getQuerySettingList(-1);
    }
}
